package dispatcher

import(
	//"sanguo/cs"
	"github.com/sniperHW/kendynet"
	"github.com/sniperHW/kendynet/event"
	//cs_msg "sanguo/protocol/cs/message"
	codecs "sanguo/codec/cs"
	"fmt"
	"reflect"
	"github.com/golang/protobuf/proto"
)

type handler func()

type Dispatcher struct {
	evHandler  *event.EventHandler
}

func (this *Dispatcher) Register(ev interface{},once bool,callback interface{}) {
	switch ev.(type) {
	case string :
		this.evHandler.Register(ev,once,callback)
		break
	case proto.Message:
		msgName := reflect.TypeOf(ev).String()
		this.evHandler.Register(msgName,once,callback)
		//fmt.Println("Register",msgName)//,this.evHandler)
		break
	default:
		break
	}
}

func (this *Dispatcher) Dispatch(session kendynet.StreamSession,msg *codecs.Message) {
	if nil != msg {
		name := msg.GetName()
		//fmt.Println("dispatch",name)//,this.evHandler)
		this.evHandler.Emit(name,session,msg)
		//fmt.Println("dispatch",name,"ok")//,this.evHandler)
	}
}

func (this *Dispatcher) OnClose(session kendynet.StreamSession,reason string) {
	this.evHandler.Emit("Close",session,reason)
}

func (this *Dispatcher) OnEstablish(session kendynet.StreamSession) {
	fmt.Println("OnEstablish")	
	this.evHandler.Emit("Establish",session)
}

func (this *Dispatcher) OnConnectFailed(peerAddr string,err error) {
	fmt.Println("OnConnectFailed",err)
	this.evHandler.Emit("ConnectFailed",peerAddr,err)
}

func New(processQueue *event.EventQueue) *Dispatcher {
	return &Dispatcher {
		evHandler : event.NewEventHandler(processQueue),
	}
}
